// 1. React核心库
import React, { useState, useRef, useCallback, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Modal, Space, Tag, Popconfirm } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, ApiOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';



// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 业务组件
import ProviderForm from './components/ProviderForm';
import ProviderDetail from './components/ProviderDetail';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIProvider } from '@/services/generated';

const AIProviderList: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<AIProvider | null>(null);
  const [testData, setTestData] = useState<AIProvider[]>([]);
  const actionRef = useRef<ActionType>();

  // 测试数据获取
  useEffect(() => {
    const testFetch = async () => {
      console.log('测试数据获取...');
      try {
        const result = await fetchProviders({ current: 1, pageSize: 10 }, {}, {});
        console.log('测试获取结果:', result);
        if (result.success && result.data) {
          setTestData(result.data);
        }
      } catch (error) {
        console.error('测试获取失败:', error);
      }
    };
    testFetch();
  }, []);

  // 获取提供商列表
  const fetchProviders = async (params: any, sort: any, filter: any) => {
    console.log('fetchProviders被调用');
    console.log('参数:', params);
    console.log('排序:', sort);
    console.log('过滤:', filter);

    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatProvidersList({
        page: params.current || 1,
        pageSize: params.pageSize || 10,
        search: params.search,
        providerType: params.provider_type,
        isActive: params.is_active,
      });

      console.log('API响应:', response);

      if (!response.data) {
        console.error('响应中没有data字段');
        return { data: [], success: false, total: 0 };
      }

      const items = response.data.items || [];
      const total = response.data.total || 0;

      console.log('解析的数据项:', items);
      console.log('解析的总数:', total);

      const result = {
        data: items,
        success: true,
        total: total,
      };

      console.log('最终返回给ProTable的数据:', result);
      return result;

    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      return { data: [], success: false, total: 0 };
    }
  };

  // 删除提供商
  const handleDelete = useCallback(async (id: number) => {
    try {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatProvidersDestroy({ id: String(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  }, []);

  // 测试连接
  const handleTestConnection = useCallback(async (record: AIProvider) => {
    try {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatProvidersTestConnectionCreate({
        id: String(record.id!),
        aIProviderTestRequest: {
          provider_id: record.id!,
          test_message: 'Hello, this is a test message.',
        },
      });
      message.success('连接测试成功');
    } catch (error) {
      message.error('连接测试失败');
    }
  }, []);

  // 表格列定义
  const columns: ProColumns<AIProvider>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      
      search: false,
    },
    {
      title: '提供商名称',
      dataIndex: 'name',
      
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '请输入提供商名称' }],
      },
    },
    {
      title: '提供商类型',
      dataIndex: 'provider_type',
       
      valueType: 'select',
      valueEnum: {
        openai: { text: 'OpenAI', status: 'Processing' },
        anthropic: { text: 'Anthropic', status: 'Success' },
        google: { text: 'Google', status: 'Warning' },
        custom: { text: '自定义', status: 'Default' },
      },
      render: (_, record) => {
        const typeMap = {
          openai: { color: 'blue', text: 'OpenAI' },
          anthropic: { color: 'green', text: 'Anthropic' },
          google: { color: 'orange', text: 'Google' },
          custom: { color: 'default', text: '自定义' },
        };
        const type = typeMap[record.provider_type as keyof typeof typeMap];
        return <Tag color={type?.color}>{type?.text}</Tag>;
      },
    },
    {
      title: 'API端点',
      dataIndex: 'api_endpoint',
      
      ellipsis: true,
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
       
      valueType: 'select',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={record.is_active ? 'green' : 'red'}>
          {record.is_active ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '公开',
      dataIndex: 'is_public',
      
      valueType: 'select',
      valueEnum: {
        true: { text: '公开', status: 'Processing' },
        false: { text: '私有', status: 'Default' },
      },
      render: (_, record) => (
        <Tag color={record.is_public ? 'blue' : 'default'}>
          {record.is_public ? '公开' : '私有'}
        </Tag>
      ),
      search: false,
    },
    {
      title: '创建时间',
      colSize: 8,
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
    },
  
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'left',
      // width: 100,
      // colSize: 8,
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => {
            setCurrentRecord(record);
            setDetailModalVisible(true);
          }}
        >
          详情
        </Button>,
        <Button
          key="test"
          type="link"
          size="small"
          icon={<ApiOutlined />}
          onClick={() => handleTestConnection(record)}
        >
          测试
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => {
            setCurrentRecord(record);
            setEditModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除这个提供商吗？"
          onConfirm={() => handleDelete(record.id!)}
          okText="确定"
          cancelText="取消"
        >
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'AI提供商管理',
        subTitle: '管理AI服务提供商配置',
      }}
    >
     

      <ProTable<AIProvider>
        headerTitle="AI提供商列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 'max-content'}}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            新建提供商
          </Button>,
        ]}
        request={fetchProviders}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        options={{
          reload: true,
          density: true,
          setting: true,
        }}
        dateFormatter="string"
      />

      {/* 新建提供商Modal */}
      <Modal
        title="新建AI提供商"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={800}
      >
        <ProviderForm
          onSuccess={() => {
            setCreateModalVisible(false);
            actionRef.current?.reload();
          }}
          onCancel={() => setCreateModalVisible(false)}
        />
      </Modal>

      {/* 编辑提供商Modal */}
      <Modal
        title="编辑AI提供商"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={800}
      >
        <ProviderForm
          initialValues={currentRecord}
          onSuccess={() => {
            setEditModalVisible(false);
            actionRef.current?.reload();
          }}
          onCancel={() => setEditModalVisible(false)}
        />
      </Modal>

      {/* 提供商详情Modal */}
      <Modal
        title="AI提供商详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        <ProviderDetail data={currentRecord} />
      </Modal>
    </PageContainer>
  );
};

export default AIProviderList;
